import { getUrlParam } from "/@/utils"
import { useUserStore } from "/@/store/modules/user"
import { useGlobSetting } from "/@/hooks/setting"
import * as authApi from "/@/api/auth/index"
import * as cacheService from "/@/utils/cache/module"
import { isLoginPage, PageEnum } from "/@/enums/pageEnum"
import * as utils from '/@/utils'
import * as iamCache from "/@/utils/cache/module/iam"
import { RequestHeaderEnum } from "/@/enums/httpEnum"
import { ErrorCode } from '/@/enums/iamEnum'
import { WorkspaceTypeEnum } from "/@/enums/iamEnum"
const MESSAGE_MODEL = "messageModel"
const glob = useGlobSetting()
const callbackPath = PageEnum.OAUTH_CALLBACK
const SSO_APP_ERROR_PAGE = "/exception/appError";
const getWorkspaceType = () => getUrlParam('workspaceType') || getUrlParam('workspace_type')

interface IamOption {
  loginTimoutCallback?: Function
  // 用户重新登录过的回调, 一般用于刷新页面
  reLoginCallback?: Function
}

interface RequestHeaderConfig {
  terminal?: string
  loginType?: string
  originEndpoint?: string
}

export function useIam(options?: IamOption) {
  const locationUrl = "http://" + window.location.host + "/"

  function getAppId() {
    const href = window.location.href
    return getUrlParam("app_id", href) || getUrlParam("appId", href) || iamCache.getAppId() || glob.appId
  }

  const getPublicConfig = () => {
    return iamCache.getPublicConfig()
  }

  const getWorkspaceType = (): string => {
    return iamCache.getWorkspaceType()
  }

  const isAppHubOrMgt = (): boolean => {
    const workspaceType = getWorkspaceType()
    return workspaceType == WorkspaceTypeEnum.APP_MGT || workspaceType == WorkspaceTypeEnum.APP_GOVERN_HUB
  }

  const getTenantId = () => {
    const href = window.location.href
    return getUrlParam("tenant_id", href) || getUrlParam("tenantId", href) || iamCache.getSelectTenant()?.id
  }

  const fillRequestHeader = (globSetting: RequestHeaderConfig, headers: object) => {
    const loginId = iamCache.getLoginId()

    // 如果接口指定了租户id, 就使用指定的
    if (!headers[RequestHeaderEnum.TENANT_ID]) {
      headers[RequestHeaderEnum.TENANT_ID] = getTenantId()
    }

    const appPublicConfig = getPublicConfig() || {} as any
    // headers[RequestHeaderEnum.CLIENT_ID] = globSetting.oauth2ClientId
    headers[RequestHeaderEnum.TERMINAL] = globSetting.terminal
    headers[RequestHeaderEnum.LOGIN_TYPE] = globSetting.loginType
    headers[RequestHeaderEnum.ORIGIN_ENDPOINT] = globSetting.originEndpoint
    headers[RequestHeaderEnum.LOGIN_ID] = loginId
    // if (!headers[RequestHeaderEnum.APP_ID]) {
    //   headers[RequestHeaderEnum.APP_ID] = getAppId() || appPublicConfig.id
    // }
  }


  const checkLogin = async (isLoginConfirm = true, isFirst = false) => {
    const tenantId = getTenantId()
    const appId = getAppId()
    console.info('tenantId', tenantId)
    console.info('appId', appId)
    if (!tenantId || !appId) {
      console.error('tenantId or appId is null')
      redirectLogin(false)
      return
    }

    const result = await authApi.checkLogin({ isFirst, tenantId })
    console.log('checkLoginResult', result, 'isFirst', isFirst)
    if (result.success) {
      // if(result.reLoginFlag)
      if (isFirst) {
        iamCache.setLoginId(result.data.loginId)
      }
      iamCache.setWorkspaceType(result.data.appId, result.data.workspaceType)
      iamCache.setAppId(result.data.appId)
      iamCache.setSelectTenant({
        id: result.data.tenantId
      })
      sessionStorage.removeItem(MESSAGE_MODEL)
      return
    }
    if (result.code == ErrorCode.TOKEN_EXPIRED) {
      redirectLogin(isLoginConfirm)
    } else if (result.code == ErrorCode.SESSION_EXPIRED) {
      if (isFirst) {
        iamCache.setLoginId(result.data.loginId)
      }
      if (options?.reLoginCallback && typeof options.reLoginCallback === 'function') {
        const value = sessionStorage.getItem(MESSAGE_MODEL)
        if (value) {
          return
        }
        options.reLoginCallback(result.msg)
        sessionStorage.setItem(MESSAGE_MODEL, '1')
      } else {
        alert(result.msg)
      }
    } else {
      result.data = result.data || {}
      result.data.appHomePageUrl = utils.deleteUrlParams(window.location.href, ['tenantId', 'appId'])
      result.data.loginRedirectUri = getRedirectUrl()
      result.data.workspaceType = cacheService.getWorkspaceType() || glob.workspaceType
      const info = encodeURIComponent(JSON.stringify(result || {}))
      if (!result.data.ssoLoginPageUrl) {
        throw new Error("检测登录异常")
      }

      // SSO_APP_ERROR_PAGE
      window.location.href = `${result.data.ssoLoginPageUrl}${SSO_APP_ERROR_PAGE}?info=${info}`
    }
  }

  const getRedirectUrl = (redirectUrl?: string) => {
    let backUrl = window.location.href
    backUrl = utils.deleteUrlParams(backUrl, ['tenantId', 'appId'])
    return window.location.protocol + "//" + window.location.host + "/oauth/callback?backUrl=" + encodeURIComponent(backUrl)
  }

  const redirectLogin = (isConfirm = true) => {
    console.log('redirectLogin')
    iamCache.clearAppId()
    const redirectUri = getRedirectUrl()
    const appId = getAppId()
    const workspaceType = cacheService.getWorkspaceType() || glob.workspaceType
    const url = `${glob.casBaseUrl}/oauth/authorize?scope=server&response_type=code&app_id=${appId}&workspace_type=${workspaceType}&redirect_uri=${encodeURIComponent(redirectUri)}`
    console.log('auth-url', url)
    if (isConfirm && options?.loginTimoutCallback && typeof options.loginTimoutCallback === 'function') {
      const value = sessionStorage.getItem(MESSAGE_MODEL)
      if (value) {
        return
      }
      console.log('开始登录')
      options.loginTimoutCallback(url)
      sessionStorage.setItem(MESSAGE_MODEL, '1')
    } else {
      window.location.href = url
    }
  }

  /**
   * 退出登录
   */
  async function ssoLogout() {
    await authApi.doLogout()
  }

  const init = async () => {
    console.log('initIam')
    iamCache.resetLoginId()
    sessionStorage.removeItem(MESSAGE_MODEL)
    document.addEventListener("visibilitychange", async () => {
      console.log('loginId', iamCache.getLoginId())
      if (document.visibilityState === 'visible') {
        checkLogin()
      }
    }, true)
    // 第一次不需要确认登录，直接跳转到登录页面
    await checkLogin(false, true)
  }

  return {
    init,
    checkLogin,
    redirectLogin,
    ssoLogout,
    getAppId,
    getTenantId,
    getPublicConfig,
    getWorkspaceType,
    isAppHubOrMgt,
    fillRequestHeader
  }
}
